/*
 * SwitchMenu.java
 * business
 *
 * Created by ChenTao on 2017/2/21.
 *
 * Copyright (c) 2017年 yidiandao. All rights reserved.
 */

package com.yidiandao.business.ui.widget.view;

import android.content.Context;
import android.content.res.TypedArray;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.yidiandao.business.R;
import com.yidiandao.business.utils.UIUtils;

/** 左右切换选择菜单 */
public class SwitchMenu extends LinearLayout implements View.OnClickListener {

    public static final int SWITCH_LEFT = 0;

    public static final int SWITCH_RIGHT = 1;

    private TextView mTvLeft;

    private TextView mTvRight;

    private OnSwitchMenuClickClickListener mListener;

    public SwitchMenu(Context context) {
        this(context, null);
    }

    public SwitchMenu(Context context, AttributeSet set) {
        super(context, set);

        View root = LayoutInflater.from(context).inflate(R.layout.item_switch_menu, this);

        mTvLeft = (TextView) root.findViewById(R.id.tv_left);
        mTvRight = (TextView) root.findViewById(R.id.tv_right);

        setSelected(true, false);

        mTvLeft.setOnClickListener(this);
        mTvRight.setOnClickListener(this);

        TypedArray typedArray = context.obtainStyledAttributes(set, R.styleable.SwitchMenu);

        int resourceId =
                typedArray.getResourceId(R.styleable.SwitchMenu_menuItems, R.array.search_title);
        setMenu(resourceId);

        typedArray.recycle();
    }

    public void setMenu(int menuId) {
        String[] title = UIUtils.getStringArray(menuId);

        if (title.length != 2) {
            throw new IllegalArgumentException("This menu must contain two items");
        }

        mTvLeft.setText(title[0]);
        mTvRight.setText(title[1]);
    }

    public void setSelected(boolean left, boolean right) {
        mTvLeft.setSelected(left);
        mTvRight.setSelected(right);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.tv_left:
                setSelected(true, false);
                if (mListener != null) {
                    mListener.onSwitchMenuClick(SWITCH_LEFT);
                }
                break;
            case R.id.tv_right:
                setSelected(false, true);
                if (mListener != null) {
                    mListener.onSwitchMenuClick(SWITCH_RIGHT);
                }
                break;
        }
    }

    public void setOnSwitchMenuClickClickListener(OnSwitchMenuClickClickListener listener) {
        mListener = listener;
    }

    public interface OnSwitchMenuClickClickListener {
        void onSwitchMenuClick(int position);
    }
}
